﻿Imports System.Security.Cryptography
Imports System.Windows.Media.Animation
Imports FuncClasses

Public Class LogInFrontPage
    Private db As IDatabase
    Public Sub New(ByRef window As Window1)

        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()
        window.AddNewWelcomeInfo(Me)
        Dim lu = window.Database.GetSettingByKey("lastuser")
        db = window.Database
        Dim usercount As Integer = window.Database.GetAllUsers.Count
        If usercount > 0 Then
            LogInTextbox1.Text = lu
            loginsp.Visibility = Windows.Visibility.Visible
        Else
            nouser.Visibility = Windows.Visibility.Visible
        End If
    End Sub

    ''' <summary>
    ''' New User
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub TextBlock_MouseUp_1(sender As Object, e As MouseButtonEventArgs)
        Dim hash As String = GetHash(Textbox1.Text + Textbox2.Password + ("truetruetruetruetruetruetruetruetrue"))
        Dim usr As New FuncClasses.nHibernate.Models.UserPreviewModel With {.Hash = hash, .UserName = Textbox1.Text, .UserID = Textbox3.Text, .CanEditUsers = True, .CanReadArticle = True, .CanReadCustomer = True, .CanReadDatabase = True, _
                                                                 .CanReadOrder = True, .CanWriteArticle = True, .CanWriteCustomer = True, .CanWriteDatabase = True, .CanWriteOrder = True}
        Try
            db.SaveOrUpdateUser(usr, Nothing)
            Dim user As New FuncClasses.User(Textbox1.Text, Textbox2.Password, db)
            db.SetSettingByKey("lastuser", Textbox1.Text)
            If user.LogInFailed = False Then
                RaiseEvent LoginSucceed(user)
            End If
            r1.Text = user.Name
        Catch
            LogInTextbox1.Text = Textbox1.Text
            LogInTextbox2.Password = Textbox2.Password
            DoLogIn()
        End Try

        Dim sb As Storyboard = FindResource("newuserout")
        AddHandler sb.Completed, AddressOf SBNewUserCompleted
        sb.Begin()

    End Sub

    ''' <summary>
    ''' Creates the hash
    ''' </summary>
    ''' <param name="input"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function GetHash(input As String) As String
        Dim dataToMAC As Byte() = System.Text.Encoding.UTF8.GetBytes(input)
        Using hmacsha1 As New HMACSHA256(System.Text.Encoding.UTF8.GetBytes("EBFD359A91C23FEC2E3267D5FAE87A37F7156C0B0524CBDE533225F10605C913"))
            Return System.Convert.ToBase64String(hmacsha1.ComputeHash(dataToMAC))
        End Using
    End Function

    Public Event LoginSucceed(usr As FuncClasses.User)

    ''' <summary>
    ''' Check if the given username - password combination is valid. If so, the user will be logged in
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub DoLogIn()
        Dim user As New FuncClasses.User(LogInTextbox1.Text, LogInTextbox2.Password, db)
        If user.LogInFailed = False Then
            RaiseEvent LoginSucceed(user)
            Dim sb As Storyboard = FindResource("loginout")
            AddHandler sb.Completed, AddressOf SBNewUserCompleted
            sb.Begin()
            r1.Text = user.Name
            db.SetSettingByKey("lastuser", user.Name)
        Else
            Loginfailedlbl.Visibility = Windows.Visibility.Visible
        End If
    End Sub

    ''' <summary>
    ''' Check if the last user has no password. If so, login will be performed automatically
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub DoSilentLogIn()
        Dim user As New FuncClasses.User(LogInTextbox1.Text, LogInTextbox2.Password, db)
        If user.LogInFailed = False Then
            RaiseEvent LoginSucceed(user)
            Dim sb As Storyboard = FindResource("loginout")
            AddHandler sb.Completed, AddressOf SBNewUserCompleted
            sb.Begin()
            r1.Text = user.Name
            db.SetSettingByKey("lastuser", user.Name)
        Else
        End If
    End Sub

    ''' <summary>
    ''' Login Click
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub TextBlock_MouseUp_2(sender As Object, e As MouseButtonEventArgs)
        DoLogIn()
    End Sub

    ''' <summary>
    ''' Login Enter
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub LogInTextbox2_KeyUp(sender As Object, e As KeyEventArgs) Handles LogInTextbox2.KeyUp
        If e.Key = Key.Enter Then
            DoLogIn()
        End If
    End Sub

    Private Sub SBNewUserCompleted()
        nouser.Visibility = Windows.Visibility.Collapsed
        loginsp.Visibility = Windows.Visibility.Collapsed
        loggedinassp.Visibility = Windows.Visibility.Visible
        Dim sb As Storyboard = FindResource("loginout")
        sb.Seek(TimeSpan.FromSeconds(0))
        sb.Stop()
        sb = FindResource("loggedinassb")
        sb.Begin()
    End Sub

    ''' <summary>
    ''' Abmelden
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub TextBlock_MouseUp_3(sender As Object, e As MouseButtonEventArgs)
        RaiseEvent LoginSucceed(Nothing)
        loginsp.Visibility = Windows.Visibility.Visible
        loggedinassp.Visibility = Windows.Visibility.Collapsed
    End Sub

    Private Sub Grid_Loaded_1(sender As Object, e As RoutedEventArgs)
        DoSilentLogIn()
    End Sub
End Class
